package user;

import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.collections.set.SynchronizedSet;

import com.fasterxml.jackson.databind.ObjectMapper;

import common.PhoneCode;

/**
 * Servlet implementation class CodeController
 */
@WebServlet("/CodeController")
public class CodeController extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public CodeController() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @return 
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		//response.getWriter().append("Served at: ").append(request.getContextPath());
		response.setContentType("text/html; charset=UTF-8");
		response.setCharacterEncoding("utf-8");
		request.setCharacterEncoding("utf-8");
		HttpSession session = request.getSession();
		String phone = request.getParameter("phone");
		String result = null;
		try {
			 result = SendCode.sendCode(phone, "14883048");
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		ObjectMapper om = new ObjectMapper();
        PhoneCode phoneCode = om.readValue(result, PhoneCode.class);
        System.out.println(phoneCode);
        System.out.println(phoneCode.getCode());
        String code = phoneCode.getObj();
        System.out.println(code);
        if(phoneCode.getCode()==200){
        	session.setAttribute("code", code);
            //设置session的最大存活时间为三分钟，也就是验证码有效期在session中3分钟
            session.setMaxInactiveInterval(60*3);
        }

	}
	
	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doGet(request, response);
	}

}
